﻿#region System
using System;
using System.Collections.Generic;
using CF.Framework.Engine.Controls;
using CF.Framework.Engine.Drawing;
using CF.Framework.Engine.Effects;
using CF.Framework.Engine.Screens;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion

namespace CF.Framework.Engine.Screens
{
	public class FadeInOutScreen : GameScreen
	{
		private TimeSpan sleep = TimeSpan.Zero;
		private Background background;
		private FadeInEffect fadeInEffect;
		private FadeOutEffect fadeOutEffect;

		public Texture2D BackgroundImage { get; set; }

		protected override void OnLoadContent()
		{
			base.OnLoadContent();

			fadeInEffect = new FadeInEffect() { Duration = TimeSpan.FromSeconds(1) };
			fadeOutEffect = new FadeOutEffect() { Duration = TimeSpan.FromSeconds(1) };

			fadeOutEffect.EffectEnd += new EventHandler(fadeOutEffect_EffectEnd);
		}

		void fadeOutEffect_EffectEnd(object sender, EventArgs e)
		{
			this.ExitScreen();
		}

		protected override void OnReady()
		{
			base.OnReady();

			if (BackgroundImage != null)
			{
				background = new Background() { Opacity = 0, Context = BackgroundImage, Style = BackgroundStyle.Stretch, OpacityMask = DrawingUtility.CreateRectangleTexture(ScreenManager.GraphicsDevice, ScreenManager.ScreenWidth, ScreenManager.ScreenHeight, Color.Black) };
				background.Effects.Add(fadeInEffect);
				background.Effects.Add(fadeOutEffect);

				this.Components.Add(background);

				fadeInEffect.Start();
			}
			else
			{
				this.ExitScreen();
			}
		}

		protected override void OnUpdate(GameTime gameTime)
		{
			base.OnUpdate(gameTime);

			if (!fadeInEffect.IsDoing 
				&& !fadeOutEffect.IsRunning
				&& sleep < TimeSpan.FromSeconds(3))
			{
				sleep += gameTime.ElapsedGameTime;

				if (sleep >= TimeSpan.FromSeconds(3))
				{
					fadeInEffect.Stop();
					fadeOutEffect.Start();
				}
			}
		}

		protected override void OnDraw(GameTime gameTime, SpriteBatch spriteBatch)
		{
			base.OnDraw(gameTime, spriteBatch);
		}
	}
}
